import * as vscode from 'vscode';
import { analyzeCode } from './codeAnalyzer';
import { speakText } from './speechService';

export function activate(context: vscode.ExtensionContext) {
    console.log('Code Reader extension is now active!');

    // Register the main command
    const analyzeCommand = vscode.commands.registerCommand('code-reader.analyzeCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('No active editor found!');
            return;
        }

        const document = editor.document;
        const selection = editor.selection;
        const startLine = selection.start.line + 1;
        const endLine = selection.end.line + 1;

        // Get the selected code
        const selectedCode = document.getText(selection);
        
        // If no selection, get the current line
        let codeToAnalyze = selectedCode;
        if (!codeToAnalyze.trim()) {
            const currentLine = document.lineAt(selection.active.line);
            codeToAnalyze = currentLine.text;
            
            // If still empty, try to get a broader context
            if (!codeToAnalyze.trim()) {
                const range = new vscode.Range(
                    Math.max(0, selection.active.line - 2),
                    0,
                    Math.min(document.lineCount, selection.active.line + 3),
                    0
                );
                codeToAnalyze = document.getText(range);
            }
        }

        try {
            // Show progress indicator
            await vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "Analyzing code with AI...",
                cancellable: false
            }, async (progress) => {
                const analysis = await analyzeCode(codeToAnalyze);
                
                // Format the analysis result
                const message = `Lines ${startLine}-${endLine} implement ${analysis}`;
                
                // Speak the analysis
                await speakText(message);
                
                // Show in status bar
                vscode.window.setStatusBarMessage(message, 5000);
                
                // Show in output channel
                const outputChannel = vscode.window.createOutputChannel('Code Reader');
                outputChannel.appendLine(message);
                outputChannel.show();
            });
        } catch (error) {
            vscode.window.showErrorMessage(`Error analyzing code: ${error}`);
        }
    });

    // Register a command to show the TTS panel
    const ttsPanelCommand = vscode.commands.registerCommand('code-reader.showTtsPanel', () => {
        // This will be handled by the speechService
        vscode.window.showInformationMessage('TTS Panel will be shown here');
    });

    context.subscriptions.push(analyzeCommand, ttsPanelCommand);
}

export function deactivate() {}